/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package datos;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author Alejandro
 */
public class Mysql {

    static private Mysql singleton = null;

    static public Mysql getSingleton() {

        if (singleton == null) {
            singleton = new Mysql("localhost", "alejandro", "a1425lex", "gupea");
        }
        return singleton;
    }
    private String user;
    private String password;
    private String db;
    private String host;
    private String url;
    private boolean exito = false;
    private Connection session;
    private Statement stm;
    private Mysql(String server, String usuario, String contraseña, String bd) {
        this.user = usuario;
        this.password = contraseña;
        this.db = bd;
        this.host = server;
        this.url = "jdbc:mysql://" + this.host + "/" + this.db;
    }
    private boolean open()
    {
        try {
            Class.forName("org.gjt.mm.mysql.Driver");
            session = DriverManager.getConnection(url, user, password);
            if (session != null) {
                System.out.println("Conexión a base de datos " + url + " … Ok");
                stm = session.createStatement();
                return true;
            } else {
                return false;
            }
        } catch (SQLException ex) {
            System.out.println("Hubo un problema al intentar conectarse con la base de datos " + url);
            return false;
        } catch (ClassNotFoundException ex) {
            System.out.println(ex);
            return false;
        }
    }
    private void close() throws SQLException
    {
        session.close();
        stm.close();
    }
    public ResultSet query(String query) throws SQLException
    {
        this.open();
        ResultSet rs =  stm.executeQuery(query);
        this.close();
        return rs;
    }
    public ResultSet callStoreProcedure(String procedureName, String arguments[]) throws SQLException
    {
        this.open();
        ResultSet rs = this.stm.executeQuery("CALL "+procedureName+"("+this.arguments(arguments)+")");
        return rs;
    }
    private String arguments(String arguments[])
    {
        String prepareArguments = "";
        for(String argument:arguments)
            prepareArguments += isNumber(argument) ? Long.parseLong(argument)+"," : "'"+argument+"',";
        return prepareArguments.substring(0,prepareArguments.length()-1);
    }
    private boolean isNumber(String string)
    {
        try{
            Long.parseLong(string);
        }catch (Exception e)
        {
            return false;
        }
        return true;
    }
}
